package com.shunwang.tools.httpclientsupport.client;

import java.io.IOException;
import java.util.List;

import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientNode extends AbstractHttpClientNode {

	private static Logger logger = LoggerFactory.getLogger(HttpClientNode.class);
	
	public HttpClientNode(HttpClientInfo clientInfo) {
		super(clientInfo);
	}

	public String sendPost(NameValuePair[] pair) throws HttpException, IOException{
		if(pair == null){
			if(logger.isInfoEnabled()){
				logger.info("pairs is null");
			}
			return null;
		}
		PostMethod method = new PostMethod(getInfo().toString());
//		PostMethod method = getMethod();
		method.setRequestBody(pair);
		if(logger.isDebugEnabled()){
			logger.debug("client preRun");
		}
		getClient().executeMethod(method);
		if(logger.isDebugEnabled()){
			logger.debug("client run over");
		}
		String returnString = new String(method.getResponseBody(),getEncode());
		if(logger.isDebugEnabled()){
			logger.debug(returnString);
		}
		method.releaseConnection();
		return returnString;
	}

	@Override
	public String sendPost(NameValuePair pair) throws HttpException, IOException {
		if(pair == null){
			if(logger.isInfoEnabled()){
				logger.info("pair is null");
			}
			return null;
		}
		return sendPost(new NameValuePair[]{pair});
	}

	@Override
	public String sendPost(List<NameValuePair> pair) throws HttpException, IOException {
		NameValuePair[] pairs = new NameValuePair[pair.size()];
		return sendPost(pair.toArray(pairs));
	}
}
